﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using Microsoft.EntityFrameworkCore;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler
{
    public class GetProductionCascaderHandler : IRequestHandler<GetProductionCascaderCommand, ApiResult<object>>
    {
        private readonly IRepository<ProduceModel> _produceRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;

        public GetProductionCascaderHandler(
            IRepository<ProduceModel> produceRepo,
            IRepository<MaterialGroupModel> materialGroupRepo)
        {
            _produceRepo = produceRepo;
            _materialGroupRepo = materialGroupRepo;
        }

        public async Task<ApiResult<object>> Handle(GetProductionCascaderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<object>();

            // 1. 获取所有生产工单
            var productions = await _produceRepo.GetAll()
                .Select(p => new
                {
                    Id = p.Id,
                    Code = p.ProduceCode,
                    Name = p.ProduceName,
                    MaterialGroupId = p.MaterialGroupId,
                    ProduceNum = p.ProduceNum // 生产数量（用于检测数量默认值）
                })
                .ToListAsync(cancellationToken);

            // 2. 获取所有物料群组
            var materialGroups = await _materialGroupRepo.GetAll()
                .Select(g => new
                {
                    Id = g.Id,
                    Code = g.MaterialGroupCode,
                    Name = g.MaterialGroupName
                })
                .ToListAsync(cancellationToken);

            // 3. 构建联动数据格式
            var data = new
            {
                Productions = productions,
                MaterialGroups = materialGroups
            };

            return result.Success("获取成功", data);
        }
    }
}
